package IOStream_etc.ConversionFlow_etc;

import org.junit.Test;

import java.io.*;

/**
 * @author Jimmy Zhan WORKSTATION
 * @date 2023/3/29 15:16
 * 说明：
 */

public class InputStreamReaderTest {
    @Test
    public void test1() throws IOException {
        // 创建File对象
        File file1 = new File("Any_utf-8.txt");

        // 创建流对象
        FileInputStream fis = new FileInputStream(file1);
        // 此时默认使用的是IDEA使用的UTF-8字符集
//        InputStreamReader isr = new InputStreamReader(fis);
        InputStreamReader isr = new InputStreamReader(fis, "utf-8");

        // 读入操作
        char[] cBuffer = new char[1024];
        int len;
        while((len = isr.read(cBuffer)) != -1){
            String str = new String(cBuffer, 0, len);
            System.out.println(str);
        }

        // 关闭资源
        isr.close();

    }

    /**
     * 将GBK格式的文件转换为utf-8格式的文件存储
     */
    @Test
    public void test2() throws IOException{
        // 1. 造文件
        File file1 = new File("AnyGBK.txt");
        File file2 = new File("AnyGBKtoUTF-8.txt");

        // 2. 造流
        FileInputStream fis = new FileInputStream(file1);
        FileOutputStream fos = new FileOutputStream(file2);
        InputStreamReader isr = new InputStreamReader(fis, "gbk");
        OutputStreamWriter osw = new OutputStreamWriter(fos, "utf-8");

        // 3. 读写过程
        char[] cBuffer = new char[1024];
        int len;
        while((len = isr.read(cBuffer)) != -1){
            osw.write(cBuffer, 0, len);
        }

        if (osw != null) osw.close();
        if (isr != null) isr.close();
    }
}
